<template>
  <div class="test-center">
    <!-- 顶部栏 -->
    <div class="test-center__header">
      <div class="header-left">
        <h2 class="test-center__title">测试中心</h2>
        <!-- 教材选择器 -->
        <el-select
          v-model="selectedProgramId"
          placeholder="选择教材"
          style="width: 200px"
          @change="onProgramChange"
        >
          <el-option
            v-for="program in localProgramList"
            :key="program.id"
            :label="program.nameZhCn"
            :value="program.id"
          />
        </el-select>
      </div>

      <!-- 功能切换 -->
      <div class="header-right">
        <el-radio-group v-model="activeTab" @change="onTabChange">
          <el-radio-button label="test-center">测试中心</el-radio-button>
          <el-radio-button label="test-records">测试记录</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 内容区域 -->
    <div v-loading="loading" class="test-center__content">
      <!-- 测试中心 -->
      <div v-if="activeTab === 'test-center'" class="test-section">
        <el-table :data="localUnitTestList" style="width: 100%" :stripe="true">
          <el-table-column prop="unitName" label="单元名称" />
          <el-table-column prop="totalWords" label="单词数量" width="100" />
          <el-table-column label="测试状态" width="120">
            <template #default="{ row }">
              <el-tag :type="row.isCompleted ? 'success' : 'info'">
                {{ row.isCompleted ? '已完成' : '未完成' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="lastTestScore" label="最后得分" width="100">
            <template #default="{ row }">
              <span
                v-if="row.lastTestScore"
                :class="getScoreClass(row.lastTestScore)"
              >
                {{ row.lastTestScore }}分
              </span>
              <span v-else class="no-score">--</span>
            </template>
          </el-table-column>
          <el-table-column prop="testCount" label="测试次数" width="100" />
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="startTest(row)">
                开始测试
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <Pagination
            v-model:page="unitTestPagination.pageNum"
            v-model:limit="unitTestPagination.pageSize"
            :total="unitTestTotal"
            @pagination="fetchUnitTestList"
          />
        </div>
      </div>

      <!-- 测试记录 -->
      <div v-if="activeTab === 'test-records'" class="test-section">
        <el-table
          :data="localTestRecordList"
          style="width: 100%"
          :stripe="true"
        >
          <el-table-column prop="unitName" label="单元名称" width="200" />
          <el-table-column prop="score" label="测试分数" width="100">
            <template #default="{ row }">
              <span :class="getScoreClass(row.score)">
                {{ row.score }}分
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="timeConsuming" label="用时" width="80">
            <template #default="{ row }">
              {{ row.timeConsuming }}秒
            </template>
          </el-table-column>
          <el-table-column label="错误单词" min-width="150">
            <template #default="{ row }">
              <div class="word-list error-words">
                <el-tag
                  v-for="word in row.wrongWordSpellings"
                  :key="word"
                  type="danger"
                  size="small"
                  class="word-tag"
                >
                  {{ word }}
                </el-tag>
                <span v-if="!row.wrongWordSpellings?.length" class="empty-text">无</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="正确单词" min-width="150">
            <template #default="{ row }">
              <div class="word-list correct-words">
                <el-tag
                  v-for="word in row.rightWordSpellings"
                  :key="word"
                  type="success"
                  size="small"
                  class="word-tag"
                >
                  {{ word }}
                </el-tag>
                <span v-if="!row.rightWordSpellings?.length" class="empty-text">无</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="未选择单词" min-width="150">
            <template #default="{ row }">
              <div class="word-list unchoose-words">
                <el-tag
                  v-for="word in row.unchooseWordSpellings"
                  :key="word"
                  type="info"
                  size="small"
                  class="word-tag"
                >
                  {{ word }}
                </el-tag>
                <span v-if="!row.unchooseWordSpellings?.length" class="empty-text">无</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="viewTestDetail(row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <Pagination
            v-model:page="testRecordPagination.pageNum"
            v-model:limit="testRecordPagination.pageSize"
            :total="testRecordTotal"
            @pagination="fetchTestRecordList"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import Pagination from '@/components/Pagination/index.vue'
import { useDcyxTestCenterStoreHook, useDcyxProgramStoreHook, useDcyxUnitStoreHook } from '@/store'
import type {
  UnitTestItem,
  TestRecordItem,
} from '@/api/dcyx/test-center.api'
import type { ProgramItem } from '@/api/dcyx/program.api'

defineOptions({
  name: 'TestCenter',
  inheritAttrs: false,
})

const router = useRouter()
const route = useRoute()
const testCenterStore = useDcyxTestCenterStoreHook()
const programStore = useDcyxProgramStoreHook()
const unitStore = useDcyxUnitStoreHook()

// 响应式数据
const activeTab = ref<'test-center' | 'test-records'>('test-center')
const selectedProgramId = ref<number>(0)
const loading = ref(false)

// 本地数据
const localUnitTestList = ref<UnitTestItem[]>([])
const localTestRecordList = ref<TestRecordItem[]>([])
const localProgramList = ref<ProgramItem[]>([])

// 分页数据
const unitTestPagination = ref({
  pageNum: 1,
  pageSize: 10,
})

const testRecordPagination = ref({
  pageNum: 1,
  pageSize: 10,
})

// 计算属性
const unitTestTotal = computed(() => testCenterStore.unitTestTotal)
const testRecordTotal = computed(() => testCenterStore.testRecordTotal)

// 获取单元测试列表
async function fetchUnitTestList() {
  if (!selectedProgramId.value) return

  try {
    loading.value = true
    const list = await testCenterStore.fetchUnitTestList({
      programId: selectedProgramId.value,
      pageNum: unitTestPagination.value.pageNum,
      pageSize: unitTestPagination.value.pageSize,
    })
    localUnitTestList.value = list
  } catch (error) {
    console.error('获取单元测试列表失败:', error)
    ElMessage.error('获取单元测试列表失败')
  } finally {
    loading.value = false
  }
}

// 获取测试记录列表
async function fetchTestRecordList() {
  if (!selectedProgramId.value) return

  try {
    loading.value = true
    const list = await testCenterStore.fetchTestRecordList({
      programId: selectedProgramId.value,
      pageNum: testRecordPagination.value.pageNum,
      pageSize: testRecordPagination.value.pageSize,
    })
    localTestRecordList.value = list
  } catch (error) {
    console.error('获取测试记录列表失败:', error)
    ElMessage.error('获取测试记录列表失败')
  } finally {
    loading.value = false
  }
}

// 获取教材列表
async function fetchProgramList() {
  try {
    const currentSeriesId = programStore.currentSeriesId
    if (!currentSeriesId) {
      console.error('当前系列ID不存在')
      return
    }

    const list = await programStore.getProgramBySeriesId(currentSeriesId)
    localProgramList.value = list

    // 设置默认选中的教材
    if (list.length > 0 && !selectedProgramId.value) {
      selectedProgramId.value = programStore.currentProgramId || list[0].id
    }
  } catch (error) {
    console.error('获取教材列表失败:', error)
    ElMessage.error('获取教材列表失败')
  }
}

// 教材切换
function onProgramChange() {
  unitTestPagination.value.pageNum = 1
  testRecordPagination.value.pageNum = 1

  if (activeTab.value === 'test-center') {
    fetchUnitTestList()
  } else {
    fetchTestRecordList()
  }
}

// 标签切换
function onTabChange() {
  if (activeTab.value === 'test-center') {
    fetchUnitTestList()
  } else {
    fetchTestRecordList()
  }
}

// 开始测试
async function startTest(unitTest: UnitTestItem) {
  try {
    // 直接跳转到测试试卷页面
    router.push(`/work/test-paper/${unitTest.unitId}`)
  } catch (error) {
    console.error('开始测试失败:', error)
    ElMessage.error('开始测试失败')
  }
}

// 查看测试详情
function viewTestDetail(testRecord: TestRecordItem) {
  router.push(`/dcyx/work-main/test-detail/${testRecord.id}`)
}

// 获取分数样式类
function getScoreClass(score: number): string {
  if (score >= 90) return 'score-high'
  if (score >= 60) return 'score-medium'
  return 'score-low'
}

// 初始化测试中心
async function initTestCenter() {
  try {
    // 先检查 programStore 是否有 currentProgram 的值
    if (!programStore.currentProgram || !programStore.currentProgram.programId) {
      console.log('programStore.currentProgram 不存在，开始初始化...')
      // 参考 word-training.vue 的实现方式，先初始化 unitStore，然后初始化 programStore
      await unitStore.initUnitStore()
      await programStore.initProgramStore()
    }

    // 获取教材列表
    await fetchProgramList()

    // 根据当前标签页加载对应数据
    if (activeTab.value === 'test-center') {
      fetchUnitTestList()
    } else {
      fetchTestRecordList()
    }
  } catch (error) {
    console.error('initTestCenter - 初始化测试中心失败:', error)
    ElMessage.error('初始化应用数据失败，请稍后重试')
  }
}

// 监听路由查询参数变化，用于刷新数据
watch(
  () => route.query.refresh,
  (newRefresh, oldRefresh) => {
    if (newRefresh && newRefresh !== oldRefresh) {
      console.log('检测到刷新参数，重新加载数据')
      refreshTestCenterData()
    }
  }
)

// 刷新测试中心数据
async function refreshTestCenterData() {
  try {
    console.log('刷新测试中心数据')

    // 根据当前标签页刷新对应数据
    if (activeTab.value === 'test-center') {
      await fetchUnitTestList()
      ElMessage.success('测试数据已刷新')
    } else {
      await fetchTestRecordList()
      ElMessage.success('测试记录已刷新')
    }
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败')
  }
}

onMounted(() => {
  initTestCenter()
})
</script>

<style lang="scss" scoped>
.test-center {
  padding: 20px;
  height: 100%;
  background-color: var(--el-bg-color-page);

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .header-left {
      display: flex;
      align-items: center;
      gap: 20px;
    }

    .header-right {
      display: flex;
      align-items: center;
    }
  }

  &__title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }

  &__content {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }
}

.test-section {
  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}

.score {
  font-weight: 600;

  &-high {
    color: var(--el-color-success);
  }

  &-medium {
    color: var(--el-color-warning);
  }

  &-low {
    color: var(--el-color-danger);
  }
}

.no-score {
  color: var(--el-text-color-placeholder);
}

// 单词列表样式
.word-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  max-height: 60px;
  overflow-y: auto;

  .word-tag {
    margin: 0;
    font-size: 12px;
  }

  .empty-text {
    color: var(--el-text-color-placeholder);
    font-size: 12px;
    font-style: italic;
  }
}

.error-words {
  .word-tag {
    background-color: var(--el-color-danger-light-8);
    border-color: var(--el-color-danger-light-6);
    color: var(--el-color-danger);
  }
}

.correct-words {
  .word-tag {
    background-color: var(--el-color-success-light-8);
    border-color: var(--el-color-success-light-6);
    color: var(--el-color-success);
  }
}

.unchoose-words {
  .word-tag {
    background-color: var(--el-color-info-light-8);
    border-color: var(--el-color-info-light-6);
    color: var(--el-color-info);
  }
}
</style>
